﻿//https://leetcode.cn/problems/copy-list-with-random-pointer/submissions/590257559/?envType=study-plan-v2&envId=top-100-liked

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node* cur = head;
        map<Node*, Node*> nodeMap;
        Node* copyhead = nullptr, * copytail = nullptr;
        //复制
        while (cur)
        {
            Node* newnode = new Node(cur->val);
            if (copyhead == nullptr)
                copyhead = copytail = newnode;
            else
            {
                copytail->next = newnode;
                copytail = newnode;
            }
            nodeMap.insert({ cur,newnode });
            cur = cur->next;
        }

        //随机指针的链接
        cur = head;
        Node* copy = copyhead;
        while (cur)
        {
            if (cur->random == nullptr) copy->random = nullptr;
            else
            {
                copy->random = nodeMap[cur->random];
            }
            cur = cur->next;
            copy = copy->next;
        }
        return copyhead;
    }
};